﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ConsumeSys.Orm;
using System.Threading.Tasks;
using ConsumeSys.Model;

namespace ConsumeSys.Controllers
{
    [IsLogin]
    public class ConsumeController : BaseController
    {
        /// <summary>
        /// 实例化消费业务逻辑
        /// </summary>
        private ConsumeSys.BLL.ConsumeBLL b_ConsumeBLL = new BLL.ConsumeBLL();
        /// <summary>
        /// 用户业务逻辑
        /// </summary>
        private ConsumeSys.BLL.UserBLL b_UserBLL = new BLL.UserBLL();

        #region 消费类型

        public async Task<ActionResult> AEConsumeType()
        {
            await Task.Run(() =>
            {
                List<Model.ConsumeType> list = b_ConsumeBLL.GetConsumeTypeList();
                ViewData["list"] = list;
            });
            return View();
        }

        /// <summary>
        /// 添加或编辑消费类型
        /// </summary>
        /// <param name="consumeType">ConsumeType</param>
        /// <returns></returns>
        public async Task<ContentResult> GetAEConsumeType(Model.ConsumeType consumeType)
        {
            return await Task.Run(() =>
            {
                int count = b_ConsumeBLL.AddConsumeType(consumeType);
                if (count > 0)
                {
                    return Content("success");
                }
                return Content("fail");
            });
        }
        /// <summary>
        /// 添加消费类型列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">页大小</param>
        /// <param name="typeName">类型名称</param>
        /// <returns></returns>
        public async Task<ActionResult> ConsumeTypeList()
        {
            return await Task.FromResult<ActionResult>(base.View());
        }

        /// <summary>
        /// 消费类型列表
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">页大小</param>
        /// <param name="typeName">类型名称</param>
        /// <returns></returns>
        public async Task<ContentResult> GetConsumeTypeList(int? page, int? rows, string typeName)
        {
            return await Task.Run(() =>
            {
                Paging<Model.ConsumeType> _paging = b_ConsumeBLL.GetConsumeTypePaging(page.ToInt32(), rows.ToInt32(), typeName);
                Dictionary<string, object> jsonMap = new Dictionary<string, object>();
                jsonMap.Add("total", _paging.RecordCount);
                jsonMap.Add("rows", _paging.DataList);
                string jsonStr = jsonMap.ToJson();
                return Content(jsonStr);
            });
        }


        /// <summary>
        /// 删除消费类型
        /// </summary>
        /// <param name="ids">主键集合</param>
        /// <returns></returns>
        public async Task<ContentResult> DeleteConsumeType(string ids)
        {
            return await Task.Run(() =>
            {
                int count = b_ConsumeBLL.DeleteConsumeType(ids);
                if (count > 0)
                {
                    return Content("success");
                }
                return Content("error");
            });
        }

        #endregion

        #region 消费

        public async Task<ActionResult> ConsumeList()
        {
            return await Task.FromResult<ActionResult>(base.View());
            //return View();  
        }

        /// <summary>
        /// 获取分页信息
        /// </summary>
        /// <param name="page">页码</param>
        /// <param name="rows">页大小</param>
        /// <param name="c_Name">名称</param>
        /// <param name="c_SettlementStatus">结算状态</param>
        /// <param name="c_UserId">消费人</param>
        /// <param name="c_CTypeId">类型</param>
        /// <returns></returns>
        public async Task<ContentResult> GetConsumeList(string c_Name, int c_SettlementStatus = 1, int c_UserId = 0, int c_CTypeId = 0, int page = 1, int rows = 10)
        {
            return await Task.Run(() =>
            {
                Paging<Model.Consume> _paging = b_ConsumeBLL.GetConsumePaging(page, rows, c_Name, c_SettlementStatus, c_UserId, c_CTypeId);
                Dictionary<string, object> jsonMap = new Dictionary<string, object>();
                jsonMap.Add("total", _paging.RecordCount);
                jsonMap.Add("rows", _paging.DataList);
                string jsonStr = jsonMap.ToJson();
                return Content(jsonStr);
            });
        }

        public async Task<ActionResult> AEConsume()
        {
            return await Task.Run(() =>
            {
                //消费类型
                List<Model.ConsumeType> typeList = b_ConsumeBLL.GetConsumeTypeList();
                ViewData["typeList"] = typeList;
                //用户集合
                List<Model.User> userList = b_UserBLL.GetUserList();
                ViewData["userList"] = userList;
                return View();
            });
        }

        /// <summary>
        /// 添加消费
        /// </summary>
        /// <param name="c_Name"></param>
        /// <param name="c_CTypeId"></param>
        /// <param name="c_UserId"></param>
        /// <param name="c_TotalPrice"></param>
        /// <param name="c_ActualPayment"></param>
        /// <param name="c_PersonTotalCount"></param>
        /// <param name="c_Remark"></param>
        /// <param name="c_CTime"></param>
        /// <returns></returns>
        public async Task<ActionResult> AddConsume(string c_Name, int? c_CTypeId, int? c_UserId, double? c_TotalPrice, double? c_ActualPayment, int? c_PersonTotalCount, string c_Remark, string c_CTime)
        {
            try
            {
                #region 数据验证

                if (string.IsNullOrWhiteSpace(c_Name))
                {
                    throw new Exception("消费名称不能为空！");
                }
                if (c_CTypeId.ToInt32() == 0)
                {
                    throw new Exception("请选择消费类型！");
                }
                if (c_UserId.ToInt32() == 0)
                {
                    throw new Exception("请选择消费人（付钱人）！");
                }
                //if (c_TotalPrice.ToDouble() <= 0)
                //{
                //    throw new Exception("请输入合法的消费总金额！");
                //}
                if (c_ActualPayment.ToDouble() <= 0)
                {
                    throw new Exception("请输入合法的实际付款金额！");
                }
                if (c_PersonTotalCount.ToInt32() <= 0)
                {
                    throw new Exception("请输入合法的参与总人数！");
                }
                if (string.IsNullOrWhiteSpace(c_CTime))
                {
                    throw new Exception("请输入消费时间！");
                }

                #endregion
                int count = 0;
                var loginUser = b_UserBLL.GetLoginUser();
                string inputPerson = loginUser.u_RealName;
                int userId = loginUser.id;

                await Task.Run(() =>
                {
                    Model.Consume consume = new Model.Consume();
                    consume.c_Name = c_Name;
                    consume.c_CTypeId = c_CTypeId.ToInt32();
                    consume.c_UserId = c_UserId.ToInt32();
                    //consume.c_TotalPrice = c_TotalPrice.ToDouble();
                    consume.c_ActualPayment = c_ActualPayment.ToDouble();
                    consume.c_PersonTotalCount = c_PersonTotalCount.ToInt32();
                    consume.c_Remark = c_Remark;
                    consume.c_CTime = Convert.ToDateTime(c_CTime);
                    consume.c_SettlementStatus = (int)ConsumeSys.Enum.ConsumeEnum.SettlementStatus.未结算;
                    consume.c_InputPerson = inputPerson;
                    consume.c_InputTime = DateTime.Now;

                    //创建人id  2019-11-13 22:41:54 王浩力 添加
                    consume.c_CreateUserId = userId;

                    count = b_ConsumeBLL.AEConsume(consume);
                });
                if (count > 0)
                {
                    return Json(new Result() { Code = 200, Msg = "操作成功" });
                }
                else
                {
                    return Json(new Result() { Code = 500, Msg = "操作失败" });
                }
            }
            catch (Exception ex)
            {
                return Json(new Result() { Code = 500, Msg = ex.Message });
                //return Content("sdfdsfds:" + ex.Message);
            }
        }

        /// <summary>
        /// 删除消费
        /// </summary>
        /// <param name="ids">主键集合</param>
        /// <returns></returns>
        public async Task<ActionResult> DeleteConsume(string ids)
        {
            return await Task.Run(() =>
            {
                try
                {
                    var result = b_ConsumeBLL.DeleteConsume(ids,LoginUser);
                    return Json(result);
                }
                catch (Exception ex)
                {
                    return Json(new Result() { Code = 500, Msg = ex.Message });
                }
            });
        }

        #endregion


        //执行结算
        public ActionResult RunJieSuan()
        {
            return View();
        }

        //往期结算结果
        public ActionResult LiShiJieSuanRecords()
        {
            return View();
        }

        /// <summary>
        /// 结算消费
        /// </summary>
        /// <returns></returns>
        public async Task<string> JiSuan()
        {
            object dt = null;
            await Task.Run(() =>
            {
                dt = b_ConsumeBLL.JiSuan();
            });
            System.Data.DataTable dt2 = dt as System.Data.DataTable;
            if (dt2 != null)
            {
                if (dt2.Rows.Count == 0)
                {
                    return "0";
                }
            }
            string json = dt.ToJson();
            return json;
        }

        /// <summary>
        /// 往期计算记录
        /// </summary>
        /// <returns></returns>
        public async Task<string> OldJiSuanRecords()
        {
            return await Task.Run(() =>
            {
                object dt = b_ConsumeBLL.GetPageData();
                string json = dt.ToJson();
                return json;
            });
        }


    }
}
